package cn.pugle.base.nio;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.RunnerException;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;

/**
 * @author tzp
 * @since 2020/9/7
 */
@Warmup(iterations = 2)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MMapTest {
    public static void main(String[] args) throws RunnerException {
//        Options options = new OptionsBuilder()
//                .include(MMapTest.class.getSimpleName())
//                .forks(1)
//                .build();
//        Collection<RunResult> results = new Runner(options).run();
//        System.out.println(results.iterator().next());

        read2();
    }


    @Benchmark
    @Measurement(iterations = 3)
    public static void read1() {
        try (RandomAccessFile file = new RandomAccessFile(new File("/Users/tzp/Downloads/异度之刃2 设定画集.zip"), "r")) {
            //Get file channel in read-only mode
            FileChannel fileChannel = file.getChannel();
//            System.out.println(fileChannel.size());
            //Get direct byte buffer access using channel.map() operation
            MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY,
                    0, fileChannel.size());

            // the buffer now reads the file as if it were loaded in memory.
//            System.out.println(buffer.isLoaded());  //prints false
//            System.out.println(buffer.capacity());  //Get the size based on content size of file

            //You can read the file from this buffer the way you like.
            buffer.position(200 * 1024 * 1024);
            for (int i = 0; i < 4; i++) {
//                System.out.print((char) buffer.get()); //Print the content of file
            }
//            System.out.println("\n-------");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Benchmark
    @Measurement(iterations = 3)
    public static void read2() {
        try (RandomAccessFile file = new RandomAccessFile(new File("/Users/tzp/Downloads/异度之刃2 设定画集.zip"), "r")) {
            //Get file channel in read-only mode
            FileChannel fileChannel = file.getChannel();
//            System.out.println(fileChannel.size());
            fileChannel.position(200 * 1024 * 1024);

            ByteBuffer bb = ByteBuffer.allocate(4);
            fileChannel.read(bb);
            bb.flip();
            for (int i = 0; i < bb.limit(); i++) {
                System.out.print((char) bb.get());
            }
            System.out.println("\n-------");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Benchmark
    @Measurement(iterations = 3)
    public static void read3() {

    }
}
